import Vue from 'vue';
import Router from 'vue-router';
import VueRouter from 'vue-router';
import routes from './routes'; // 路由数据
import store from '@/store/index';
import { filterAsyncRouter } from '@/utils/filter-routes';
import { getContextData } from '@csii/vx-util';

Vue.use(Router);
const router = new Router({
  mode: 'hash',
  scrollBehavior() {
    if (document.querySelector('.ui-theme-container-main')) {
      //进入下一个页面后，上下滚动条默认置顶
      document.querySelector('.ui-theme-container-main').scrollTop = 0;
    }
    // 使用 keep-alive后 scrollBehavior 不起作用
    return {
      x: 0,
      y: 0,
    };
  },
  routes,
});

// 解决重复点击菜单报错 Uncaught (in promise) NavigationDuplicated{_name: "NavigationDuplicated", name: "NavigationDuplicated"}
const originalPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//   if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
//   return originalPush.call(this, location).catch((err) => err);
// };
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  /* 这里暂时将cookie里是否存有token作为验证是否登录的条件,请根据自身业务需要修改*/
  const token = getContextData('token');
  if (to.meta.skipAuth) {
    next();
  } else {
    // 判断是否是登录状态
    if (token && token !== 'undefined') {
      // 获取menu菜单列表
      let menu = await store.dispatch('vxadmin/menu/loadMenu');
      if (!menu) {
        next({
          name: 'login',
          query: {
            redirect: to.fullPath,
          },
        });
      } else {
        await getAccountData();
        //如果访问/的地址，就将路由跳转到该用户拥有的菜单权限的第一个菜单页
        if (to.path === '/') {
          for (let index = 0; index < menu.length; index++) {
            if (menu[index].children === null) {
              return next(menu[index].component);
            } else {
              return next(menu[index].children[0].component);
            }
          }
        }
        next();
        // loadMenus(menu, next, to);
      }
    } else {
      /* 没有登录的时候跳转到登录界面, 携带上登陆成功之后需要跳转的页面完整路径*/
      next({
        name: 'login',
        query: {
          redirect: to.fullPath,
        },
      });
    }
  }
});

router.afterEach((to) => {
  // 存储当前所在页面路由信息
  store.commit('vxadmin/page/setPage', to);
});

async function getAccountData() {
  if (JSON.stringify(store.state.vxadmin.user.info) === '{}') {
    // 获取用户信息
    await store.dispatch('vxadmin/user/load');
  }
  if (!store.state.vxadmin.menu.menuList.length) {
    // 获取菜单表
    let menu = await store.dispatch('vxadmin/menu/loadMenu');
    store.commit('vxadmin/menu/menuSet', menu);
  }
}

export const loadMenus = (menu, next, to) => {
  const asyncRouter = filterAsyncRouter(menu);
  asyncRouter.push({ path: '*', redirect: '/404', hidden: true });
  // 存储路由
  router.addRoute(asyncRouter); // 动态添加可访问路由表
  next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
};

export default router;
